package com.boguan.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.boguan.common.core.domain.entity.SysUser;
import com.boguan.common.utils.SMSVerification;
import com.boguan.common.utils.SecurityUtils;
import com.boguan.common.utils.StringUtils;
import com.boguan.common.utils.VerifyCodeUtils;
import com.boguan.system.domain.vo.Register;
import com.boguan.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.boguan.common.constant.Constants;
import com.boguan.common.core.domain.AjaxResult;
import com.boguan.common.core.redis.RedisCache;
import com.boguan.common.utils.sign.Base64;
import com.boguan.common.utils.uuid.IdUtils;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@Api(tags = "验证码相关")
@RestController
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    // 验证码类型
    @Value("${project.captchaType}")
    private String captchaType;

    @Autowired
    private SMSVerification smsVerification;

    @Autowired
    private ISysUserService userService;

    /**
     * 生成验证码
     */
    @ApiOperation("生成验证码")
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();

            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));

        return ajax;
    }


    /**
     * 生成忘记密码的短信验证码
     */
    @ApiOperation("生成忘记密码的短信验证码")
    @PostMapping("/retrieve/password/code")
    public AjaxResult retrievePasswordCode(@RequestBody Register register) {
        SysUser user = userService.selectUserByUserName(register.getUsername());
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("用户信息不存在");
        }
        if (!user.getPhonenumber().equals(register.getPhonenumber())) {
            return AjaxResult.error("您输入的手机号与您预留的不一致");
        }
        Integer count = redisCache.getCacheObject(Constants.RETRIEVE_PASSWORD_CODE_COUNT + user.getPhonenumber());
        if (StringUtils.isNull(count)) {
            count = 0;
        } else if (count >= 5) {
            return AjaxResult.error("今日验证码已经达到最大数量，请明天再试");
        }
        String code = VerifyCodeUtils.generateVerifyCode(6, "1234567890");
        boolean flag = smsVerification.SMSSendVerificationCode("及时星", user.getPhonenumber(), "SMS_205256067", code);
        if (flag) {
            //保存短信验证码
            count += 1;
            redisCache.setCacheObject(Constants.RETRIEVE_PASSWORD_CODE + user.getPhonenumber(), code, 5 * 60, TimeUnit.SECONDS);
            redisCache.setCacheObject(Constants.RETRIEVE_PASSWORD_CODE_COUNT + user.getPhonenumber(), count, 2 * 60 * 60, TimeUnit.SECONDS);
        } else {
            return AjaxResult.error("短信验证码发送失败，请稍后重试");
        }
        return AjaxResult.success();
    }


    /**
     * 修改手机号验证码获取
     */
    @ApiOperation("修改手机号验证码获取")
    @GetMapping("/update/phone/code")
    public AjaxResult updatePhoneCode() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer count = redisCache.getCacheObject(Constants.UPDATE_PHONE_CODE_COUNT + user.getPhonenumber());
        if (StringUtils.isNull(count)) {
            count = 0;
        } else if (count >= 5) {
            return AjaxResult.error("今日验证码已经达到最大数量，请明天再试");
        }
        String code = VerifyCodeUtils.generateVerifyCode(6, "1234567890");
        boolean flag = smsVerification.SMSSendVerificationCode("及时星", user.getPhonenumber(), "SMS_205256067", code);
        if (flag) {
            //保存短信验证码
            count += 1;
            redisCache.setCacheObject(Constants.UPDATE_PHONE_CODE + user.getPhonenumber(), code, 5 * 60, TimeUnit.SECONDS);
            redisCache.setCacheObject(Constants.UPDATE_PHONE_CODE_COUNT + user.getPhonenumber(), count, 24 * 60 * 60, TimeUnit.SECONDS);
        } else {
            return AjaxResult.error("短信验证码发送失败，请稍后重试");
        }
        return AjaxResult.success();
    }

    /**
     * 验证码登录获取验证码信息
     */
    @ApiOperation("登录验证码获取")
    @GetMapping("/login/code")
    public AjaxResult loginCode(String phone) {
        Integer count = redisCache.getCacheObject(Constants.LOGIN_CODE_NUM + phone);
        if (StringUtils.isNull(count)) {
            count = 0;
        } else if (count >= 5) {
            return AjaxResult.error("今日验证码已经达到最大数量，请明天再试");
        }
        String code = VerifyCodeUtils.generateVerifyCode(6, "1234567890");
        boolean flag = smsVerification.SMSSendVerificationCode("及时星",phone, "SMS_205256067", code);
        if (flag) {
            //保存短信验证码
            count += 1;
            redisCache.setCacheObject(Constants.LOGIN_CODE + phone, code, 20 * 60, TimeUnit.SECONDS);
            redisCache.setCacheObject(Constants.LOGIN_CODE_NUM + phone, count,  60 * 60, TimeUnit.SECONDS);
        } else {
            return AjaxResult.error("短信验证码发送失败，请稍后重试");
        }
        return AjaxResult.success();
    }

}
